package jxau.jwgl.web.controller;

import jxau.jwgl.service.NotLoginException;
import jxau.jwgl.utils.ConvertUtil;
import jxau.jwgl.web.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * BaseController
 *
 * @author LongShu 2017/06/04
 */
public abstract class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String SESSION_USER_KEY = "loginUser";
    public static final String SESSION_GUID_KEY = "jwglGuid";

    public <T> T getLoginUser(HttpServletRequest request) {
        T user = getSessionAttribute(request, SESSION_USER_KEY);
        if (user == null) {
            throw new NotLoginException("请先登录!");
        }
        return user;
    }

    @SuppressWarnings("unchecked")
    public <T> T getSessionAttribute(HttpServletRequest request, String name) {
        return (T) request.getSession().getAttribute(name);
    }

    public void setSessionAttribute(HttpServletRequest request, String name, Object value) {
        request.getSession().setAttribute(name, value);
    }

    public String getUserAgent(HttpServletRequest request) {
        String userAgent = WebUtil.getUserAgent(request);
        logger.debug("userAgent:{}", userAgent);
        return userAgent;
    }

    public boolean isIE(HttpServletRequest request) {
        String userAgent = getUserAgent(request);
        return WebUtil.isIE(userAgent);
    }

    /**
     * 判断是否为异步请求
     */
    public boolean isAjax(HttpServletRequest request) {
        return WebUtil.isAjax(request);
    }

    public boolean isMultipartContent(HttpServletRequest request) {
        return WebUtil.isMultipartContent(request);
    }

    public Boolean toBoolean(String value) {
        try {
            return ConvertUtil.toBoolean(value);
        } catch (RuntimeException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public Integer toInt(String value) {
        try {
            return ConvertUtil.toInt(value);
        } catch (RuntimeException e) {
            throw new RuntimeException("Can not parse [" + value + "] to Integer value.");
        }
    }

    public Long toLong(String value) {
        try {
            return ConvertUtil.toLong(value);
        } catch (RuntimeException e) {
            throw new RuntimeException("Can not parse [" + value + "] to Long value.");
        }
    }

}
